package com.temple.common.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.util.Map;

@Slf4j
public class HttUtlis<T> {
    /**
     * 默认contenttype(提交类型)
     */
    public static MediaType CONTENTTYPE = MediaType.APPLICATION_FORM_URLENCODED;

//    private volatile static HttUtlis instance;
//
//    public static HttUtlis getInstance() {
//        if (null == instance) {
//            synchronized (HttUtlis.class) {
//                if (null == instance) {
//                    instance = new HttUtlis<T>();
//                }
//            }
//        }
//        return instance;
//    }
//
//    private <T>HttUtlis() {
//
//    }


    T post(Map<String, String> param, Class<T> tClass, String url) {

        RestTemplate restTemplate = new RestTemplate();
//       String url = "http://client.sms10000.com/api/webservice";
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(CONTENTTYPE);
        MultiValueMap<String, String> map = new LinkedMultiValueMap<>();

        for (Map.Entry<String, String> entry : param.entrySet()) {
            log.error("-----------请求参数："+entry.getKey()+"-------------------请求值："+entry.getValue());
            map.add(entry.getKey(), entry.getValue());
        }

        HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(map, headers);
        ResponseEntity<T> response = restTemplate.postForEntity(url, request, tClass);
        log.info("请求返回结果---------------：{}"+response.getBody());
        return response.getBody();


    }


   T get(String uri, Class<T> tClass,Map<String,String> param){

        RestTemplate restTemplate = new RestTemplate();
        StringBuilder url = new StringBuilder(uri);
        if(null != param && !param.isEmpty()){
            for(Map.Entry<String,String> entry:param.entrySet()){
                url.append(entry.getKey()+"&="+entry.getValue());
            }
        }

       ResponseEntity<T> result = restTemplate.getForEntity(url.toString(), tClass);
       log.info("请求返回结果---------------："+result.getBody());
        return result.getBody();
    }


//    public static void main(String [] args){
//        String url = "http://apis.map.qq.com/ws/geocoder/v1/?location=" + "22.52291" + "," + "114.05454" + "&key=" + "UR5BZ-4TZCD-L6M4B-HUHIZ-6ELLK-3RB4M" + "&get_poi=1";
//
//        HttUtlis httUtlis = new HttUtlis();
//
//        httUtlis.get(url,String.class,null);
//
//    }
}
